# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
通达信历史数据
"""
import datetime
from typing import List


import sys
sys.path.append("../../")
from bangth_utils.mysql_database import MySQL
from bangth_utils.future.futureklinedata import CFutureKlineItem, CFutureKlineStore


class TdxData:
    def __init__(self, file_name):
        self.file_name = file_name
        self.lines = None
        self.bars: List[CFutureKlineItem] = list()
        self.code = None

    def read_history_data(self, n=0):
        with open(self.file_name) as f:
            f.readline()
            f.readline()
            self.lines = f.readlines()
            self.lines = self.lines[:-1]
            if n != 0:
                self.lines = self.lines[-n:]
            print("get history end.")

    def parse_data(self, code):
        self.bars.clear()
        self.code = code
        for line in self.lines:
            a = line.split(",")
            bar = CFutureKlineItem()
            bar.date_time = datetime.datetime.strptime("{} {}".format(a[0], a[1]), "%Y/%m/%d %H%M")
            bar.open = float(a[2])
            bar.high = float(a[3])
            bar.low = float(a[4])
            bar.close = float(a[5])
            bar.volume = float(a[6])
            bar.close_oi = float(a[7])
            bar.open_oi = float(a[7])
            self.bars.append(bar)

    def save_data(self, mysql, table_name):
        store = CFutureKlineStore()
        store.replace_into_future_history_table(mysql, table_name, self.bars, self.code)


def save_if_2005(file_name=r'C:\new_tdx\T0002\export\47#IF88.txt'):
    t1 = TdxData(file_name)
    t1.read_history_data()
    t1.parse_data(file_name[file_name.find('#')+1:file_name.find('.')])
    mysql = MySQL("hqdb")
    t1.save_data(mysql, "tbl_future_kline_min5")


if __name__ == '__main__':
    save_if_2005()
